a
<template>
  <div class="app-container">
    <div slot="header" class="back">
      <router-link :to="{name: 'tools-list'}">
        <el-button plain icon="el-icon-back" size="small" :round="true">
          返回
        </el-button>
      </router-link>
    </div>
    <div class="container">
      <div class="container-content">
        <img src="../../assets/images/fk.png">
        <div class="content">
          <div class="container_top">
            <span class="container_title">Facebook Multi Pixels</span>
          </div>
          <div style="color:#7e849c;font-size:14px">这是一款基于 Facebook Pixel 的数据追踪上报工具，支持多 Pixel
            绑定你的网站，且支持按商品专辑绑定，方便你去衡量每个商品专辑的广告投放收益
          </div>
        </div>
      </div>
    </div>
    <el-form ref="form" :inline="true" :model="dataTracking" :rules="rules" size="small">
      <el-form-item label="" prop="bindValue">
        <el-input v-model="dataTracking.bindValue" placeholder="输入Pixel" style="width: 260px"></el-input>
      </el-form-item>
      <el-form-item label="">
        <el-select v-model="dataTracking.seriesId" @change="setBindType" style="width: 260px">
          <el-option :value="null" label="全局"></el-option>
          <el-option
              v-for="item in series"
              :key="item.value"
              :label="item.label"
              :value="item.value">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button size="mini" type="primary" @click="handleAddDataTracking">添加</el-button>
      </el-form-item>
    </el-form>
    <table-pagination
        ref="el-search-table"
        :showOperatingButton="false"
        :columns="columns"
        :fetch="getData"
        :form-options="formOptions"
        :page-sizes="[20, 50, 100]"
        height="200"
        list-field="records"
        method="get"
        page-index-key="page"
        page-size-key="pageSize"
        total-field="totalElements"
        type="remote">
      <el-table-column slot="append" label="操作" width="300px">
        <template slot-scope="scope">
          <el-button plain size="mini" type="primary" @click="handleToken(scope.row.id)">配置token</el-button>
          <el-button plain size="mini" type="primary" @click="handleDelDataTracking(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </table-pagination>
    <el-dialog title="token设置" :visible.sync="tokenVisible" width="600px" center>
      <el-form ref="tokenForm" :model="tokenConfig">
        <el-form-item label="" prop="token">
          <el-input type="textarea" v-model="tokenConfig.token" placeholder="请输入token"/>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
         <el-button @click="tokenVisible = false">取 消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="postToken('tokenForm')">确 定</el-button>
    </span>
    </el-dialog>
    <div class="footer">
      <div><span style="color:red">*</span>使用须知：</div>
      <div>1.在使用本插件的同时，请确保不要同时使用其它 Facebook pixel 数据追踪插件，否则可能收到重复的、不准确的数据报告</div>
      <div>2.全局类的 Pixel 支持上报主页及全部子页面的数据，数量限制为 4 个；关联商品专辑的 Pixel 支持上报专辑页及子页面的数据，数量限制为 8 个</div>
    </div>
  </div>
</template>

<script>
import TablePagination from '_c/Tables/table-pagination';
import {
    getAppDataTracking, saveAppDataTracking, delAppDataTrackingById,
    getAppDataTrackingById, updateAppDataTracking
} from '@/api/app-market';
import {getSeriesList} from '@/api/goods';

export default {
    name: 'data-tracking-fb',
    components: {TablePagination},
    data () {
        return {
            dataTrackType: 'FB',
            tokenVisible: false,
            fixOption: {fixedHeader: true},
            tokenConfig: {
                id: '',
                token: ''
            },
            formParams: {
                name: '',
                couponCode: '',
                marketingType: '',
                status: ''
            },
            rules: {
                bindValue: [
                    {required: true, message: '请输入Pixel ID', trigger: 'blur'},
                    {type: 'string', pattern: /^[0-9]+([.]{1}[0-9]{1,2})?$/, message: 'Pixel ID只能输入数字', trigger: 'blur'}
                ]
            },
            submitLoading: false,
            pageParams: {
                page: 1,
                pageSize: 20
            },
            dataTracking: {
                bindValue: '',
                dataTrackType: 'FB',
                bindType: 'all',
                seriesTitle: '',
                seriesId: ''
            },
            series: [],
            formOptions: {
                showResetBtn: false,
                showSearchBtn: false,
                inline: true,
                submitBtnText: '添加',
                size: 'small',
                resetBtnCallback: () => {
                    this.$refs['el-search-table'].fetchHandler(this.pageParams, false);
                },
                forms: []
            },
            columns: [
                {label: 'Facebook Pixel ID', prop: 'bindValue'},
                {
                    label: '绑定类型',
                    prop: 'bindType',
                    render: row => {
                        const {bindType} = row;
                        const e = {
                            all: '全局',
                            series: '系列'
                        };
                        return e[bindType];
                    }
                },
                {label: '商品专辑', prop: 'seriesTitle'}
            ]
        };
    },
    methods: {
        handleSearch () {
            this.formParams.siteId = this.siteId;
            this.$refs['el-search-table'].fetchHandler(this.pageParams, false);
        },
        handleToken (id) {
            getAppDataTrackingById(id).then((res) => {
                this.tokenConfig.id = id;
                this.tokenConfig.token = res.data.token;
            });
            this.tokenVisible = true;
        },
        postToken (name) {
            this.$refs[name].validate(valid => {
                if (valid) {
                    updateAppDataTracking(this.tokenConfig).then(res => {
                        if (res.code === '200') {
                            this.submitLoading = false;
                            this.$message.success('保存成功');
                            this.tokenVisible = false;
                            this.tokenConfig = {
                                id: '',
                                token: ''
                            };
                            this.$refs['el-search-table'].searchHandler(true);
                        }
                    }).catch(() => {
                        this.submitLoading = false;
                    });
                }
            });
        },
        setBindType (bindType) {
            this.dataTracking.dataTrackType = this.dataTrackType;

            if (bindType === null) {
                this.dataTracking.bindType = 'all';
                this.dataTracking.seriesTitle = null;
                this.dataTracking.seriesId = null;
            } else {
                this.dataTracking.bindType = 'series';
                let obj = this.series.find((item) => {
                    if (item.value === bindType) {
                        return item;
                    }
                });
                console.log(bindType + '   ' + JSON.stringify(obj));
                this.dataTracking.seriesTitle = obj.label;
                this.dataTracking.seriesId = obj.value;
            }
        },
        handleAddDataTracking () {
            this.$refs['form'].validate(valid => {
                if (valid) {
                    this.submitLoading = true;
                    this.dataTracking.siteId = this.siteId;
                    saveAppDataTracking(this.dataTracking).then(res => {
                        if (res.code === '200') {
                            this.submitLoading = false;
                            this.$message.success('新增成功');
                            this.$refs['el-search-table'].searchHandler(true);
                        }
                    }).catch(() => {
                        this.submitLoading = false;
                    });
                }
            });
        },
        handleDelDataTracking (id) {
            this.$confirm('此操作将永久删除该 Pixel ID, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.listLoading = true;
                delAppDataTrackingById(id, this.siteId).then(res => {
                    if (res.code === '200') {
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                        this.$refs['el-search-table'].searchHandler(true);
                    } else {
                        this.$message({type: 'error', message: '删除出错'});
                    }
                });
            }).catch(() => {
            });
        },
        getData () {
            return new Promise((resolve, reject) => {
                getAppDataTracking(this.dataTrackType, this.siteId).then((res) => {
                    if (res.code === '200') {
                        resolve(res.data);
                    }
                });
            });
        },
        initData () {
            this.pageParams.pageSize = 100;
            this.pageParams.siteId = this.siteId;
            getSeriesList(this.pageParams).then(res => {
                this.series = res.data;
            });
        }
    },
    mounted () {
        this.initData();
    },
    computed: {
        siteId () {
            return this.$store.state.user.siteId;
        }
    }
};
</script>

<style lang="scss" scoped>
.search-list {
  h4 {
    border-bottom: 1px solid #E8E8E8;
    margin: 0;
    margin-bottom: 10px;
    padding-bottom: 10px;
  }
}

.container {
  margin: 30px 0 40px 40px;
  padding: 0 0 0 40px;
}

.back {
  margin: 20px;
}

.container-content {
  display: flex;
  flex-direction: row;
}

.container-content img {
  height: 80px;
}

.container_top {
  margin-bottom: 10px;
}

.content {
  display: flex;
  flex-direction: column;
  line-height: 30px;
  margin-left: 20px;
}

.container_title {
  font-size: 22px;
  color: #30344f;
  font-weight: 500;
}

.setting {
  padding: 0 15px;
  color: blue;
}

.footer {
  margin: 30px 0 40px 10px;
  padding: 0 0 0 5px;
  font-size: 14px;
  color: #666;
  line-height: 30px;
}
</style>
